package com.service.impl;

import com.service.IdempotentService;
import com.service.RedisService;
import com.service.exception.IdempotentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.UUID;

@Component
public class IdempotentServiceImpl implements IdempotentService {

    @Autowired
    private RedisService redisService;

    @Override
    public String token() {
        String token=  UUID.randomUUID().toString();
        redisService.setEx(token,token,30);
        return  token;
    }

    @Override
    public boolean validateToken(String token) {
        if (!StringUtils.hasLength(token)) {
            throw new IdempotentException("请带上虎符", token);
        }

        if(!redisService.exists(token)){
            throw new IdempotentException("你是重复性的请求");
        }
        //表示token在服务端，意思就是你是合法的操作，就是第一次
        //想象成可以操作

        redisService.remove(token);

        return true;

    }
}
